﻿using FreeDream.Common;
using System.Security.Claims;
using System.Text.Json;

namespace FreeDream.WebApi
{
    /// <summary>
    /// 用户信息,services.AddSingleton<LoginUserHelper>();
    /// </summary>
    public class LoginUserHelper
    {
        public string UserId { get; set; }

        public string UserName { get; set; }

        public string LoginIp { get; set; }

        //public CurrentLoginUser(string userId, string userName, string loginIp)
        //{
        //    UserId = userId;
        //    UserName = userName;
        //    LoginIp = loginIp;
        //}
        private readonly IHttpContextAccessor _httpContextAccessor;
        public LoginUserHelper(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 获取用户身份信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public LoginUser GetLoginUser()
        {
            var context = _httpContextAccessor.HttpContext;
            var strUserId = context.User.Claims.First(m => m.Type == ClaimTypes.Sid).Value;
            var strUserName = context.User.Claims.First(m => m.Type == ClaimTypes.Name).Value;
            this.UserId = strUserId;
            this.UserName = strUserName;
            LoginUser loginUser = new LoginUser();
            loginUser = JsonSerializer.Deserialize<LoginUser>(context.User.Claims.First(m => m.Type == ClaimTypes.UserData).Value);
            return loginUser;
        }
    }
}
